package processor

import (
	"encoding/json"
	"log"
	"net"

	"github.com/clebeg/gochat/client/manager"
	"github.com/clebeg/gochat/protocol"
	"github.com/clebeg/gochat/utils"
)

// 永远在接收消息处理器
func MsgLoopReceive(conn net.Conn) (err error) {
	var loop = true
	transfor := utils.Transfer{
		Conn: conn,
	}
	for loop {
		log.Println("等待服务器发送新消息...")
		msg, err := transfor.ReceiveMsg()

		if err != nil {
			log.Printf("服务器可能失联，%v\n", err)
			break
		}

		log.Printf("接收到新的服务器消息，%v\n", msg)

		switch msg.MsgType {
		case protocol.LoginMsgType:
			respMsg := protocol.LoginMsgResp{}
			err = json.Unmarshal([]byte(msg.MsgData), &respMsg)
			if err != nil {
				log.Printf("json.Unmarshal login msg req error, %v\n", err)
				continue
			}
			if respMsg.ErrorCode == 200 {
				log.Printf("恭喜用户(%d)登录成功！\n", respMsg.LoginUsername)
				manager.CurLoginUser = respMsg.LoginUsername
				for _, up := range respMsg.OnlineUsers {
					manager.AddOnlineUser(up.Username, up)
				}
				ShowOnlineUsers()
			} else {
				log.Printf("登录状态：%d，登录失败：%s\n", respMsg.ErrorCode, respMsg.ErrorMsg)
			}
		case protocol.RegisterMsgType:
			respMsg := protocol.RegisterMsgResp{}
			err = json.Unmarshal([]byte(msg.MsgData), &respMsg)
			if err != nil {
				log.Printf("json.Unmarshal login msg req error, %v\n", err)
				continue
			}
			if respMsg.ErrorCode == 200 {
				log.Println("恭喜注册成功！")
			} else {
				log.Printf("注册状态：%d，注册失败：%s\n", respMsg.ErrorCode, respMsg.ErrorMsg)
			}
		case protocol.NotifyLoginMsgType:
			respMsg := protocol.NotifyLoginMsgResp{}
			err = json.Unmarshal([]byte(msg.MsgData), &respMsg)
			if err != nil {
				log.Printf("json.Unmarshal login msg req error, %v\n", err)
				continue
			}
			if respMsg.ErrorCode == 200 {
				log.Printf("有新用户登录，用户ID=%v\n", respMsg.OnlineUser.Username)
				manager.AddOnlineUser(respMsg.OnlineUser.Username, respMsg.OnlineUser)
			}
			ShowOnlineUsers()
		case protocol.NotifyLogoutMsgType:
			respMsg := protocol.NotifyLogoutMsgResp{}
			err = json.Unmarshal([]byte(msg.MsgData), &respMsg)
			if err != nil {
				log.Printf("json.Unmarshal login msg req error, %v\n", err)
				continue
			}
			if respMsg.ErrorCode == 200 {
				log.Printf("有用户退出登录，用户ID=%v\n", respMsg.LogoutUser.Username)
				manager.RemoveOnlineUser(respMsg.LogoutUser.Username)
			}
			ShowOnlineUsers()
		case protocol.ChatMsgType:
			respMsg := protocol.ChatMsgResp{}
			err = json.Unmarshal([]byte(msg.MsgData), &respMsg)
			if err != nil {
				log.Printf("json.Unmarshal login msg req error, %v\n", err)
				continue
			}
			log.Printf("(%d)发来新消息=%v\n", respMsg.SendUserName, respMsg.ChatData)
		default:
			log.Printf("从服务器接收到未知消息类型，%v\n", msg.MsgType)
		}
	}
	return
}
